﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;
using Models;
using System.Linq.Expressions;
using Models.PocoModel;
using System.Data.Entity.Validation;

namespace WebMvc.Areas.Models
{
    public partial class Model_UO_User
    {
        #region Method-生成验证码 GenerateValidateCode()
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public static byte[] GenerateValidateCode()
        {
            //实例化验证码
            ValidateCode validateCode = new ValidateCode();
            //生成验证码的长度
            string code = validateCode.CreateValidateCode(5);
            //将验证码赋值给Session变量
            oc.CurrentUserVcode = code;
            //创建验证码的图片
            byte[] bytes = validateCode.CreateValidateGraphic(code);
            //最后将验证码返回
            return bytes;
        }
        #endregion

        #region Method-验证用户名是否存在 ValidateLoginName(string uLoginName)
        /// <summary>
        /// 验证用户名是否存在
        /// </summary>
        /// <param name="uLoginName">用户名</param>
        /// <returns></returns>
        public static bool ValidateLoginName(string uLoginName)
        {
            var user = oc.BllSession.IUO_UserBLL.Entities.Where(u => u.ULoginName == uLoginName).ToList();
            return user.Count != 0 ? true : false;
        }
        #endregion

        #region Method-登录功能处理 LoginIn(string strLoginName, string strLoginPwd, string strYzm)
        /// <summary>
        /// 登录功能处理
        /// </summary>
        /// <param name="strLoginName">用户名</param>
        /// <param name="strLoginPwd">密码</param>
        /// <param name="strYzm">验证码</param>
        /// <returns>返回登录结果</returns>
        public static AjaxMsgModel LoginIn(string strLoginName, string strLoginPwd, string strYzm)
        {
            if (!strYzm.Equals(oc.CurrentUserVcode))
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "验证码有问题！请重新输入！",
                };
            }
            //根据登录名得到用户信息
            var cUsers = oc.BllSession.IUO_UserBLL.Entities.Where(u => u.ULoginName == strLoginName).Select(u => new
            {
                u.UId,
                u.ULoginName,
                u.UPassWord,
                u.UName,
                u.UGender,
                u.UTelephone,
                u.UProFessTitle,
                u.UDescription
            }).ToList();

            if (cUsers.Count > 0)
            {
                var cUsr = cUsers.First();
                if (cUsr != null && cUsr.UPassWord == SecurityHepler.Md5EncryptToString(strLoginPwd))
                {
                    oc.CurrentUser = new UO_User
                    {
                        UId = cUsr.UId,
                        ULoginName = cUsr.ULoginName,
                        UPassWord = cUsr.UPassWord,
                        UGender = cUsr.UGender,
                        UName = cUsr.UName
                    };
                    //保存当前用户的权限信息
                    oc.UserPermission = Model_UO_Permission.GetUserPermission(cUsr.UId);

                    //如果你在登陆的时候选择请记住我
                    //创建Cookie保存用户登录信息
                    oc.CurrentCookieLoginName = oc.CurrentUser.ULoginName;
                    Sys_LoginLog loginLog = new Sys_LoginLog();
                    loginLog.UserID = cUsr.UId;
                    loginLog.LoginName = cUsr.ULoginName;
                    loginLog.LoginState = 1;
                    loginLog.LoginIP = oc.Request.UserHostAddress;
                    loginLog.IPAddress = "";
                    loginLog.LoginTime = DateTime.Now;
                    Model_Sys_LoginLog.AddLoginLog(loginLog);

                    //返回登录成功的信息，并跳转到管理端首页
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.ok,
                        Msg = "登录成功！",
                        Data = null,
                        BackUrl = "/Admin/Home/Index"
                    };
                }
                else
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.err,
                        Msg = "密码不正确！",
                        Data = null,
                    };
                }
            }
            else
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "用户名不存在！",
                    Data = null,
                };
            }
        }
        #endregion

        #region Method-修改密码 EditUserPwd(UO_User user, string cypwd, string cxpwd, string cqpwd)
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <returns>AjaxMsgMordel实体对象</returns>
        public static AjaxMsgModel EditUserPwd(UO_User user, string cypwd, string cxpwd, string cqpwd)
        {
            UO_User userInfo = oc.BllSession.IUO_UserBLL.Entities.Where(u => u.UId == user.UId).FirstOrDefault();

            if (userInfo.UPassWord != SecurityHepler.Md5EncryptToString(cypwd.Trim()))
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "原始密码输入错误，不能修改！",
                    Data = null,
                    BackUrl = null
                };
            }

            if (cxpwd.Trim() == cypwd.Trim())
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "新密码不能与原密码相同，请重新修改！",
                    Data = null,
                    BackUrl = null
                };
            }

            if (cxpwd.Trim().Length < 6)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "新密码不能少于6位，请重新修改！",
                    Data = null,
                    BackUrl = null
                };
            }

            if (cxpwd.Trim() != cqpwd.Trim())
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "确认密码和新密码不同，请重新修改！",
                    Data = null,
                    BackUrl = null
                };
            }
            userInfo.UPassWord = SecurityHepler.Md5EncryptToString(cxpwd.Trim());
            userInfo.UUpdateTime = DateTime.Now;

            Expression<Func<UO_User, object>>[] ignoreProperties = new Expression<Func<UO_User, object>>[]{
                u=>u.UId,u=>u.UCode,u=>u.ULoginName,u=>u.UName,u=>u.UGender,u=>u.UTelephone,u=>u.UProFessTitle,
                u=>u.UDescription,u=>u.UCreateDate,u=>u.UO_UserRole,u=>u.UO_UserVipPermission
            };
            int iret = oc.BllSession.IUO_UserBLL.Modify(userInfo, ignoreProperties);
            if (iret > 0)
            {
                oc.CurrentUser = null;
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.ok,
                    Msg = "修改密码成功",
                    Data = null,
                    BackUrl = "/Login/Index?msg=editPwd"
                };
            }
            else
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "修改密码失败",
                    Data = null,
                    BackUrl = null
                };
            }
        }
        #endregion

        #region Method-判断当前用户是否登录 IsLogin()
        /// <summary>
        /// 判断当前用户是否登录
        /// </summary>
        /// <returns></returns>
        public static bool IsLogin()
        {
            if (oc.CurrentUser == null)
            {
                if (oc.CurrentCookieLoginName != null && !oc.CurrentCookieLoginName.Equals(""))
                {
                    //根据登录名得到用户信息
                    var cUsers = oc.BllSession.IUO_UserBLL.Entities.Where(u => u.ULoginName == oc.CurrentCookieLoginName).Select(u => new
                    {
                        u.ULoginName,
                        u.UPassWord
                    }).ToList().First();
                    //把用户信息再次放入Session
                    oc.CurrentUser = new UO_User
                    {
                        ULoginName = cUsers.ULoginName,
                        UPassWord = cUsers.UPassWord
                    };
                    return true;
                }
                return false;
            }
            return true;
        }
        #endregion

        #region Method-根据筛选条件查询用户 GetUsersForIQueryable(out int total, int page, int rows,string uLoginName = "", string uName = "", string uMobile = "", string sort = null, string order = null)
        /// <summary>
        /// 根据筛选条件查询用户信息
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页数目</param>
        /// <param name="uLoginName">用户名</param>
        /// <param name="uName">姓名</param>
        /// <param name="uTelephone">手机号</param>
        /// <param name="sort">排序字段</param>
        /// <param name="order">排序方向</param>
        /// <returns>根据指定条件返回用户信息</returns>
        public static IQueryable<UO_User> GetUsersForIQueryable(out int total, int page, int rows,
            string uLoginName = "", string uName = "", string uTelephone = "", int orgId = 0, string sort = null, string order = null)
        {
            total = 0;
            PropertySortCondition<UO_User> psc = null;
            if (sort == null)
            {
                psc = new PropertySortCondition<UO_User>(u => u.UId);
            }
            else
            {
                psc = new PropertySortCondition<UO_User>(sort, order.Equals("asc") ? ListSortDirection.Ascending : ListSortDirection.Descending);
            }
            List<int> orgIds = new List<int>();
            List<int> uIds = new List<int>();
            if (orgId != 0)
            {
                orgIds = Model_UO_Organization.GetOrgIdsByOrgId(orgId);
                var uoList = oc.BllSession.IUO_UserOrganizationBLL.Entities.Where(uo => orgIds.Contains(uo.OrgId));
                if (uoList != null)
                {
                    if (uoList.ToList().Count > 0)
                    {
                        uoList.ToList().ForEach(u =>
                        {
                            uIds.Add(u.UId);
                        });
                    }
                }
            }

            Expression<Func<UO_User, bool>> predicate = null;
            if (uIds.Count > 0)
            {
                predicate = u => uIds.Contains(u.UId) && u.ULoginName.Contains(uLoginName) && u.UName.Contains(uName) && u.UTelephone.Contains(uTelephone) && u.UDeleteMark == 0;
            }
            else
            {
                predicate = u => u.ULoginName.Contains(uLoginName) && u.UName.Contains(uName) && u.UTelephone.Contains(uTelephone) && u.UDeleteMark == 0;
            }
            var users = oc.BllSession.IUO_UserBLL.Entities.Where(predicate, page, rows, out total, psc);

            return users;
        }
        #endregion

        #region Method-根据筛选条件查询用户 GetUserByCondition(int page, int rows, string uLoginName = "", string uName = "", string uMobile = "", string sort = null, string order = null)
         //<summary>
         //根据筛选条件查询用户信息
         //</summary>
         //<param name="page">页码</param>
         //<param name="rows">每页数目</param>
         //<param name="uLoginName">用户名</param>
         //<param name="uName">姓名</param>
         //<param name="uMobile">手机号</param>
         //<param name="sort">排序字段</param>
         //<param name="order">排序方向</param>
         //<returns>根据指定条件返回用户信息</returns>
        public static dynamic GetUserByCondition(int page, int rows, string uLoginName = "", string uName = "", string uMobile = "", int orgId = 0, string sort = null, string order = null)
        {
            try
            {
                int total = 0;
                var users = GetUsersForIQueryable(out total, page, rows,
                uLoginName, uName, uMobile, orgId, sort, order).Select(u => new
                {
                    UId = u.UId,
                    UCode = u.UCode,
                    ULoginName = u.ULoginName,
                    UPassWord = u.UPassWord,
                    UName = u.UName,
                    UGender = u.UGender,
                    UEmail = u.UEmail,
                    UWeixin = u.UWeixin,
                    UTelephone = u.UTelephone,
                    UOrganization = u.UOrganization,
                    UQQ = u.UQQ,
                    UProFessTitle = u.UProFessTitle,
                    UDescription = u.UDescription,
                    UDeleteMark = u.UDeleteMark,
                    UCreateID = u.UCreateID,
                    UCreateName = u.UCreateName,
                    UCreateDate = u.UCreateDate,
                    UUpdateTime = u.UUpdateTime
                }).ToList();

                List<POCO_UO_User> pocoUsers = new List<POCO_UO_User>();
                foreach (var u in users)
                {
                    string orgIds = string.Empty;
                    string orgNames = string.Empty;
                    int rid = 0;
                    string roleName = string.Empty;
                    var udLists = oc.BllSession.IUO_UserOrganizationBLL.Entities.Where(ud => ud.UId == u.UId);
                    if (udLists != null)
                    {
                        if (udLists.ToList().Count > 0)
                        {
                            udLists.ToList().ForEach(r =>
                            {
                                orgIds += r.OrgId.ToString() + ",";
                                orgNames += r.UO_Organization.OrgName + ",";
                            });
                            orgIds = orgIds.Substring(0, orgIds.Length - 1);
                            orgNames = orgNames.Substring(0, orgNames.Length - 1);
                        }
                    }

                    var ridList = oc.BllSession.IUO_UserRoleBLL.Entities.Where(ur => ur.UId == u.UId);
                    if (ridList.Count() > 0)
                    {
                        rid = ridList.FirstOrDefault().RId;
                        roleName = ridList.FirstOrDefault().UO_Role.RName;
                    }

                    POCO_UO_User user = new POCO_UO_User
                    {
                        UId = u.UId,
                        UCode = u.UCode,
                        ULoginName = u.ULoginName,
                        UPassWord = u.UPassWord,
                        UName = u.UName,
                        UGender = u.UGender,
                        UEmail = u.UEmail,
                        UWeixin = u.UWeixin,
                        UTelephone = u.UTelephone,
                        UOrganization = u.UOrganization,
                        UQQ = u.UQQ,
                        UProFessTitle = u.UProFessTitle,
                        UDescription = u.UDescription,
                        UDeleteMark = u.UDeleteMark,
                        UCreateID = u.UCreateID,
                        UCreateName = u.UCreateName,
                        UCreateDate = u.UCreateDate,
                        OrgIds = orgIds,
                        OrgNames = orgNames,
                        RId = rid,
                        RName = roleName,
                        UUpdateTime = u.UUpdateTime
                    };
                    pocoUsers.Add(user);
                }

                return new DataGrid
                {
                    total = total,
                    rows = pocoUsers,
                    footer = null
                };
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        #endregion

        #region Method-新增用户 AddUser(UO_User user)
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user">新增用户</param>
        /// <returns>AjaxMsgMordel实体对象</returns>
        public static AjaxMsgModel AddUser(UO_User user)
        {
            if (ValidateLoginName(user.ULoginName))
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.ok,
                    Msg = "用户名已存在请更换！",
                    Data = null,
                    BackUrl = null
                };
            }
            try
            {
                int iret = oc.BllSession.IUO_UserBLL.Add(user);
                if (iret > 0)
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.ok,
                        Msg = "用户新增成功",
                        Data = null,
                        BackUrl = null
                    };
                }
                else
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.err,
                        Msg = "用户新增失败",
                        Data = null,
                        BackUrl = null
                    };
                }
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Method-编辑用户 EditUser(UO_User user)
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="user">编辑用户</param>
        /// <returns>AjaxMsgMordel实体对象</returns>
        public static AjaxMsgModel EditUser(UO_User user)
        {
            Expression<Func<UO_User, object>>[] ignoreProperties = new Expression<Func<UO_User, object>>[]{
                u=>u.UId,u=>u.UPassWord,u=>u.UCreateID,u=>u.UCreateName,u=>u.UCreateDate,u=>u.UUpdateTime,u=>u.UO_UserRole,u=>u.UO_UserVipPermission,u=>u.UO_UserOrganization
            };
            try
            {
                int iret = oc.BllSession.IUO_UserBLL.Modify(user, ignoreProperties);
                if (iret > 0)
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.ok,
                        Msg = "用户编辑成功",
                        Data = null,
                        BackUrl = null
                    };
                }
                else
                {
                    return new AjaxMsgModel
                    {
                        Status = AjaxStatus.err,
                        Msg = "用户编辑失败",
                        Data = null,
                        BackUrl = null
                    };
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Method-删除用户 DelUser(int uId)
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uId">删除用户</param>
        /// <returns></returns>
        public static AjaxMsgModel DelUser(int uId)
        {
            Expression<Func<UO_User, object>>[] ignoreProperties = new Expression<Func<UO_User, object>>[]{
                u=>u.UId,u=>u.UCode,u=>u.ULoginName,u=>u.UName,u=>u.UGender,u=>u.UTelephone,u=>u.UProFessTitle,
                u=>u.UEmail,u=>u.UQQ,u=>u.UWeixin,u=>u.UOrganization,u=>u.UDescription,
                u=>u.UPassWord,u=>u.UCreateID,u=>u.UCreateName,u=>u.UCreateDate,u=>u.UUpdateTime,u=>u.UO_UserRole,u=>u.UO_UserVipPermission
            };
            UO_User user = oc.BllSession.IUO_UserBLL.Entities.Where(u => u.UId == uId).FirstOrDefault();
            user.UUpdateTime = DateTime.Now;
            int iret = oc.BllSession.IUO_UserBLL.Modify(user, ignoreProperties);
            if (iret > 0)
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.ok,
                    Msg = "用户删除成功!",
                    Data = null,
                    BackUrl = null
                };
            }
            else
            {
                return new AjaxMsgModel
                {
                    Status = AjaxStatus.err,
                    Msg = "用户删除失败!",
                    Data = null,
                    BackUrl = null
                };
            }
        }
        #endregion
    }
}